﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.WebPages;

namespace ThemeText.Models
{
    public class ThemeView : IView
    {
        private string template;  //模版的目录名称 

        public ThemeView()
        {
            //this.template = "Default";
        }

        public ThemeView(string _template)
        {
            this.template = _template;
        }

        public void Render(ViewContext viewContext, TextWriter writer)
        {
            //这个地方可以自己实现，或者从 web.config 里读取，或者从用户选择的模版中读取
            //if (string.IsNullOrEmpty(template))template = "Default";

            //var sessTemp = viewContext.RequestContext.HttpContext.Session["template"];
            //if (sessTemp == null)
            //    template = this.template;

            var routeData = viewContext.RouteData;
            var controllerName = routeData.GetRequiredString("controller");
            var actionName = routeData.GetRequiredString("action");
            var areaName = routeData.DataTokens["area"] ?? null;

            string normalPath = null, tempPath = null;
            if (areaName == null)
            {
                normalPath = "~/Views/" + controllerName + "/" + actionName + ".cshtml";
                tempPath = "~/Theme/" + template + "/Views/" + controllerName + "/" + actionName + ".cshtml";
            }
            else
            {
                normalPath = "~/Areas/" + areaName + "/Views/" + controllerName + "/" + actionName + ".cshtml";
                tempPath = "~/Areas/" + areaName + "/Theme/" + template + "/Views/" + controllerName + "/" + actionName + ".cshtml";
            }

            string viewPath = normalPath;
            HttpServerUtilityBase Server = viewContext.RequestContext.HttpContext.Server;
            if (System.IO.File.Exists(Server.MapPath(tempPath)))
                viewPath = tempPath;

            Type viewType = BuildManager.GetCompiledType(viewPath);
            var page = Activator.CreateInstance(viewType) as WebViewPage;

            page.VirtualPath = viewPath;
            page.ViewContext = viewContext;
            page.ViewData = viewContext.ViewData;
            page.InitHelpers();

            WebPageContext pageContext = new WebPageContext(viewContext.HttpContext, null, null);
            WebPageRenderingBase startPage = StartPage.GetStartPage(page, "_ViewStart", new string[] { "cshtml", "vbhtml" });

            page.ExecutePageHierarchy(pageContext, writer, startPage);
        }
    }
}